/*!
 * Discuz Reader V1.0.0
 * http://code.google.com/p/discuz-reader/
 *
 * Copyright 2011, Martin Chan (Siutin)
 * http://osiutino.wordpress.com/
 * licensed under the GPL Version 3 licenses.
 * http://www.gnu.org/licenses/
 *
 *
 * Include: JQuery
 * http://jquery.com/
 * Copyright 2011, John Resig
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * 
 * Include: jQuery doTimeout
 * http://benalman.com/projects/jquery-dotimeout-plugin/
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * 
 * Date: Sun July 31 2011 06:50:26 
 */
            var $_162 = $.noConflict(true);	// avoid jQuery impaction
			
            $_162(function(){
				           
				var updateInterval = 30 * 60 * 1000;
				 
				///////////////////////////// DiscuzReader Object ////////////////////////////////////////////									
				var DzRr = {
					setting:{
						 feed_item : {"class": "feed-item"}
					},
					core: {
						makeItemTable: function(ths){		
																												
							var htmlArray=[];
							for(var i = 0 ; i < ths.length ; i++){
								var th =  $_162(ths[i]);
							
								htmlArray[i]=  "<tr><td>" + th.html() + "</td></tr>";																		
							}
							return  $_162("<table/>", {width: "100%", html: htmlArray.join('') });
						},
						makeFeed: function(){
							
							var ths = $_162("#download").html();
							
							if (ths.length == 0) return true; //wait until the page was downloaded	
														
							$_162("#download img").remove();												
							var ths = $_162("#download tbody[id^='normalthread'] th");
							
							$_162("#info").text(document.title);
							$_162("#download").empty(); //remove buffer
							$_162.method.fillDomainName(ths);
							
							$_162("#feeds").empty().append(DzRr.core.makeItemTable(ths));														
							$_162("#lastUpdated").html("Last update: " + $_162.method.GetNowDate());							
						}			
					},
					main:function(){
						
						var _url = localStorage.url;
						if (_url != undefined && _url != null && _url.length > 0) {
							
							var load = $_162("#download").hide().load(_url);
							$_162.when(load).done(function(){											
								DzRr.GetFeedsDiv().doTimeout(100, DzRr.core.makeFeed);
							})
						}				
	                	return true;
					},
					init:function(){
						
						var set_link_Btn_setting = {
							id: "SetLinkButton",							
							text: "Set Link",
							width: "100%",
							click: function(){
								var input = $_162("<input/>", set_link_tb_setting).focusout(makeSetLinkBtn);
								$_162("#control").html(input);			
								$_162("#SetLinkTextBox").focus();
							}
						};
						
						var makeSetLinkBtn = function(){
							$_162("#control").html($_162("<button/>",set_link_Btn_setting));
							//console.log(localStorage.url);
						}
					
						var saveLink = function(link){
							localStorage.url = link;
						}
						
						var set_link_tb_setting={
							type: "textbox",
							id: "SetLinkTextBox",
							width: "100%",
							keydown: function(e){
								switch (e.keyCode) {
									case 13:
							
										if ($_162(this).val().length <= 1) {
											alert("a link is required.");
											return;
										}
										
										saveLink($_162.trim($_162(this).val()));
										DzRr.main();
										makeSetLinkBtn();
										
										break;
								}
							}						
						};
										
						$_162.ajaxSetup({ cache: false });
						
						$_162("#feeds table a").die("click").live("click",function(){						
							var _url = $_162(this).attr("href");
							chrome.tabs.create({
								'url': _url
							});
						});
								
						makeSetLinkBtn();						
					},
					GetFeedsDiv: function(){
						var feedsDiv = $_162("#feeds");
						$_162("#feeds_wrap").html($_162("<div/>", {	id: "feeds"	})).children(":first-child");
						return $_162.helper.isEmpty(feedsDiv) ? feedsDiv : $_162("#feeds"); 
					}									
				};
			
				
				 ///////////////////////////////// helper /////////////////////////////////////
				 				 					
                $_162["helper"] = {
                    padLeft: function(n){
                        var s = "00" + n;
                        return s.substr(s.length - 2, 2);
                    },
					isEmpty: function(object){
						return !(object.length > 0 ? true : false);
					}
					
                };
				
                 ///////////////////////////////// method /////////////////////////////////////
				 
                $_162["method"] = {
                    GetNowDate: function(){
                        var now = new Date();
                        return now.getDate() + "/" + (now.getMonth() + 1) + "/" + (now.getYear() + 1900) + " " +
                        $_162.helper.padLeft(now.getHours()) +
                        ":" +
                        $_162.helper.padLeft(now.getMinutes()) +
                        ":" +
                        $_162.helper.padLeft(now.getSeconds());
                    },
                    GetDomainName: function(){
                        var end = localStorage.url.lastIndexOf('/') + 1;
                        return localStorage.url.substring(0, end);
                    },
                    fillDomainName: function(obj){
							//console.log(obj);
                       obj.find("a").each(function(i, item){												
                            $_162(item).attr("href", $_162.method.GetDomainName() + $_162(item).attr("href"));
                        });
                    }	
                };
				  				  
				//////////////////////////////////  MAIN //////////////////////////////////////
				
				try {
					DzRr.init();
					DzRr.main();
					
					$_162.doTimeout('updatetime', updateInterval, DzRr.main);
				}catch(ex){
					alert("ERROR: "+ex);
				}
				
				//////////////////////////////////////////////////////////////////////////////				
            });